package com.example.rpc_core.serializable.impl;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.example.rpc_core.serializable.Serializable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class HessianSerializable implements Serializable {
    /**
     * 序列化对象为 Hessian 二进制格式
     */
    @Override
    public  byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(bos);
        hessianOutput.writeObject(obj);
        return bos.toByteArray();
    }
    /**
     * 反序列化 Hessian 二进制数据为对象
     */
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        HessianInput hessianInput = new HessianInput(bis);
        return (T) hessianInput.readObject(clazz);
    }

}

